<?
/*
 * 2014/11/17
 * author by TongBC
 * Updated By Guangpeng Chen @ 2015年4月20日14:16:15
 * 外部工具查询接口类，如果手机归属地 
 *  API数据交互接口封装
 *
 */
class Api{
    const SECRET_KEY    = 'RFGrfgY5CjVP8LcY';//RFGrfgY5CjVP8LcY
    const okCode        = 200;//200 OK
    const failCode      = 106;//操作失败
    const unLogin       = 102;//未登录
    const noContentCode = 204;//204 No Content
    const badRequestCode= 400;//400 Bad Request
    const authErrorCode = 401;//401 Unauthorized
    const forbiddenCode = 403;//403 Unauthorized

    const ALERT = 'alert';
    // 手机归属地查询
    public static function mobileArea($mobile){
        $url = 'http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi';
        $result = self::file_get_curl(array('chgmobile'=>$mobile),$url);
        $result = (array)simplexml_load_string($result);
        return $result;
    }
    
    // 字符转换
    public static function iconvArr(){
    
    }
    
    // 使用 curl 发送远端请求
    public static function file_get_curl($data,$url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }



    static function AuthCheck($auth)
    {
        $limit_auth = array(
            'pft'   => 'f6a879c27ee5fd199fcb6facb6977c9685056052',
        );
        //安全性校验
        if (!in_array($auth, $limit_auth)) {
            self::Response('Auth Error', self::$authErrorCode);
        }
    }

    /**
     * 生成校验的值
     *
     * @param $authKey
     * @param $subKey
     * @return bool|string
     */
    static function SetRedisAuth($authKey, $subKey=null)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $token = self::RedisGet($authKey, $subKey);
        if (!$token) {
            $token = generate_password(8);
            if (!is_null($subKey)) {
                $redis->hSet($authKey, $subKey, $token);
                $redis->expire("$authKey", 3600);
            }
            else {
                $res = $redis->set($authKey, $token, 3600);
            }
        }
        return $token;
    }

    /**
     * 校验
     *
     * @param $authKey
     * @param $chkVal
     * @param $subKey
     * @return bool
     */
    static function ChkRedisAuth($authKey, $chkVal, $subKey=null)
    {

        $token = self::RedisGet($authKey, $subKey);
        if ($token === false || $token != $chkVal)
            return false;
        return true;
    }

    static function RedisGet($key, $subKey=null)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        if (!is_null($subKey)) {
            return $redis->hGet($key, $subKey);
        }
        return $redis->get($key);
    }

    static function SetJsonHeader()
    {
        header('Content-type: application/json');
    }

    static function Response($msg, $code, $responseType='json')
    {
        if ($responseType=='alert') {
            $alert = "{$msg}\\n错误代码:{$code}";
            $json = "<script>alert('$alert');</script>";
        } else {
            $json = '{"code":"'.$code.'", "msg":"'.$msg.'"}';
        }
        exit($json);
    }
    static function ListResponse(Array $list)
    {
        echo json_encode($list);
        exit;
    }
    static function CollectionResponse(Array $collection)
    {
        $out = array('code'=>200, 'collection'=>$collection);
        echo json_encode($out);
        exit;
    }
    static function RemoteAddress(){
        if(getenv("HTTP_CLIENT_IP")) return getenv("HTTP_CLIENT_IP");
        if(getenv("HTTP_X_FORWARDED_FOR")) return getenv("HTTP_X_FORWARDED_FOR");
        if(getenv("REMOTE_ADDR")) return getenv("REMOTE_ADDR");
    }

    static function IpChk($response=null)
    {
        $ip_list = array(
            '112.124.14.164'
        );
        $ip = self::RemoteAddress();
        if (!in_array($ip, $ip_list)) {
            self::Response('非法访问2' . $ip, self::forbiddenCode, $response);
        }
    }
    static function Log($txt,$file){
        $fp = fopen($file,"a");
        flock($fp, LOCK_EX);
        fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

    static function CacheFile($content, $file_name)
    {
        $fp = fopen($file_name,"a");
        flock($fp, LOCK_EX);
        fwrite($fp,$content);
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}
?>